package com.punch.common.page;

import cn.hutool.core.collection.CollUtil;
import com.punch.common.query.QueryInfo;

import java.util.List;

/**
 * @author tanchangguo
 * @date 2020/7/14 21:16
 */
public class PageInfo<T> {

    public static final int DEFAULT_PAGE_NO = 1;
    public static final int DEFAULT_PAGE_SIZE = 20;

    public PageInfo() {
        this.currPage = DEFAULT_PAGE_NO;
        this.pageSize = DEFAULT_PAGE_SIZE;
    }

    public PageInfo(int pageNo, int pageSize) {
        if (pageNo < 1) {
            pageNo = DEFAULT_PAGE_NO;
        }

        this.pageSize = pageSize;
        this.currPage = pageNo;
    }

    public PageInfo(QueryInfo queryInfo) {
        Integer pageNo = queryInfo.getCurrPage();
        int pageSize = queryInfo.getPageSize();
        if (pageNo == null || pageNo < 1) {
            pageNo = DEFAULT_PAGE_NO;
        }

        this.pageSize = pageSize;
        this.currPage = pageNo;
    }

    private int totalPage = 0;   //总页数
    private int totalCount = 0;  //总记录数
    private int pageSize;    //页面大小
    private int currPage;      //当前页
    private int nextPageNo;  //下一页
    private int prePageNo;   //上一页
    private List<T> data = CollUtil.newArrayList(); //数据


    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
        compute(totalCount);
    }

    private void compute(int totalCount) {
        if (pageSize != 0) {
            totalPage = totalCount / pageSize;
            if (totalCount % pageSize != 0) {
                totalPage++;
            }
        }

        if (hasNext()) {
            nextPageNo = currPage + 1;
        } else {
            nextPageNo = currPage;
        }

        if (hasPre()) {
            prePageNo = currPage - 1;
        } else {
            prePageNo = currPage;
        }
    }

    private boolean hasPre() {
        return currPage > 1;
    }

    private boolean hasNext() {
        return currPage < totalPage;
    }

    public void setData(List<T> data) {
        if (data != null) {
            this.data = data;
        }
    }

    public int getTotalPage() {
        return totalPage;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public int getPageSize() {
        return pageSize;
    }


    public int getCurrPage() {
        return currPage;
    }


    public int getNextPageNo() {
        return nextPageNo;
    }


    public int getPrePageNo() {
        return prePageNo;
    }

    public List<T> getData() {
        return data;
    }
}


